"use strict";

/**
 * 数组转树型结构
 *
 * @since 0.0.4
 * @category 树算法
 * @param {array} array 数组.
 * @param {object} config 配置参数.
 * @param {boolean} config.props 属性配置
 * @param {string} config.props.prop 数据的唯一主键key, 默认: id.
 * @param {string} config.props.parentProp 数据的父主键key, 默认: parentId.
 * @param {string} config.props.parentValue 父级的值, 根据实际传入顶层的`parentId`值 默认: undefined.
 * @param {string} config.props.childrenProp 数据的子主键key, 默认: children.
 * @param {function} config.mapping 数据转换回调函数.
 *
 * @returns { array } 转换后的树型结构数据集合
 *
 * @example
 *
 * z.treeFromArray([{ id: 1 }, { id: 2 }, { id: 3, parentId: 1 }])
 * // => [ { id: 1, children: [ { id: 3, parentId: 1 } ] }, { id: 2 } ]
 *
 * z.treeFromArray([{ code: 1, pCode: '' }, { code: 2, pCode: '' }, { code: 3, pCode: 1 }], { props: { prop: 'code', parentProp: 'pCode', parentValue: '', childrenProp: 'list' }})
 * // => [ { code: 1, pCode: '', list: [ { code: 3, pCode: '', parentId: 1 } ] }, { code: 2, pCode: '' } ]
 *
 */
function treeFromArray(array) {
  var _ref = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {},
      _ref$props = _ref.props;

  _ref$props = _ref$props === void 0 ? {} : _ref$props;
  var _ref$props$prop = _ref$props.prop,
      prop = _ref$props$prop === void 0 ? 'id' : _ref$props$prop,
      _ref$props$parentProp = _ref$props.parentProp,
      parentProp = _ref$props$parentProp === void 0 ? 'parentId' : _ref$props$parentProp,
      _ref$props$parentValu = _ref$props.parentValue,
      parentValue = _ref$props$parentValu === void 0 ? undefined : _ref$props$parentValu,
      _ref$props$childrenPr = _ref$props.childrenProp,
      childrenProp = _ref$props$childrenPr === void 0 ? 'children' : _ref$props$childrenPr,
      _ref$mapping = _ref.mapping,
      mapping = _ref$mapping === void 0 ? undefined : _ref$mapping;
  var res = [];
  array.forEach(function (item) {
    if (item[parentProp] === parentValue) {
      var children = treeFromArray(array, {
        props: {
          prop: prop,
          parentProp: parentProp,
          parentValue: item[prop],
          childrenProp: childrenProp
        },
        mapping: mapping
      });
      if (children.length) item[childrenProp] = children;
      res.push(typeof mapping === 'function' ? mapping(item) : item);
    }
  });
  return res;
}

module.exports = treeFromArray;